<?php
/**
 * jishupu-cms
 * @Author:技术铺
 * @Date:2021/11/22
 */

namespace App\Services;

/**
 * 分类树
 *
 * Class TreeService
 * @package App\Services
 */
class TreeService
{
    /**
     * 生成分类树
     * @param array $data 扁平化结构的菜单数据
     * @param string $id 默认id
     * @param string $pid 默认父id：parent_id
     * @param string $children 子集 默认children
     * @return array
     */
    public static function make($data = [], $primary_id = "id", $pid = "parent_id", $children = "children")
    {
        if (empty($data)) return [];
        $resetData = [];
        collect($data)->each(function ($item) use ($primary_id, &$resetData) {
            $resetData[$item[$primary_id]] = is_object($item) ? json_decode(json_encode($item), true) : $item;
        });
        $tree = [];
        collect($resetData)->each(function ($item, $key) use ($primary_id, $pid, $children, &$resetData, &$tree) {
            if (isset($item[$pid]) && $item[$pid] > 0) {
                $resetData[$item[$pid]][$children][] = &$resetData[$key];
            } else {
                $tree[] = &$resetData[$key];
            }
        });
        return $tree;
    }

    /**
     * 获取分类下所有子类ID集
     * @param array $data 扁平化结构的菜单数据
     * @param int $parent_id
     * @param string $primary_id
     * @param string $pid
     * @return array|int[]
     */
    public static function getSubIds($data = [], $parent_id = 0, $primary_id = "id", $pidField = "parent_id")
    {
        if (empty($data)) return [];
        $subIds = [];
        collect($data)->each(function ($item) use ($data, $parent_id, $primary_id, $pidField, &$subIds) {
            if ($item[$pidField] == $parent_id) {
                array_push($subIds, $item[$primary_id]);
                $subIds = array_merge($subIds, self::getSubIds($data, $item[$primary_id]));
            }
        });
        return $subIds;
    }

}
